package com.zjut.an.util.email;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.activation.URLDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.sun.mail.util.MailSSLSocketFactory;
import com.zjut.an.config.manager.AnConfigManager;

public class SendsimpleMail {
	    Authenticator authen = new JackAuthenticator();
	    String serverauth ="true";
	    private String mailhost=null;//SMTP邮件接收服务器
	    private String outgoingport=null;//SMTP邮件接收服务器端口号，默认为25号端口
	    private String senderadress=null;//邮件发送者的邮箱地址
	    private String senderpassword=null;//邮件发送者的邮箱密码
	    
	    /**
	    * Default constructor
	    */
	    public SendsimpleMail(String mailserver,String mailaddress,String password) {
	        mailhost=mailserver;
	        senderadress=mailaddress;
	        senderpassword=password;
	    }
	    /**
	    * ZJUT 邮箱用户发送邮件的构造方法
	    */
	    public SendsimpleMail(String mailaddress,String password) {
	        //mailhost="smtp.qq.com";
	        senderadress=mailaddress;
	        senderpassword=password;
	    }
	    
	    /**
	    * The Method sendMailWithAtt
	    * @param email_to
	    * @param email_subject
	    * @param email_body
	    * @return    boolean
	     * @throws UnsupportedEncodingException 
	     * @throws MalformedURLException 
	    */
	    public boolean sendMailWithAtt(String email_to,String email_subject, String email_body, String files) throws MalformedURLException {
	        boolean result = true;
	        try {
	            //set properties
	            Properties props = new Properties();
	            props.setProperty("mail.transport.protocol", "smtp");
	            //发送邮件服务器
	            props.setProperty("mail.host", mailhost);
	            if (serverauth != null&& serverauth.equalsIgnoreCase("true")) {
	                props.put("mail.smtp.auth", serverauth);
	            }
	            if (outgoingport!= null&& !outgoingport.trim().equals("")) {
	                props.put("mail.smtp.port", outgoingport);
	                props.put("mail.smtp.socketFactory.port",outgoingport);
	                props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
	                props.put("mail.smtp.socketFactory.fallback", "false");
	                props.setProperty("mail.smtp.quitwait", "false");
	            }
	            MailSSLSocketFactory sf = new MailSSLSocketFactory();
	            sf.setTrustAllHosts(true);
	            props.put("mail.smtp.ssl.enable", "true");
	            props.put("mail.smtp.ssl.socketFactory", sf);
	            // Get Session using Properties Object
	            Session session = null;
	            if (serverauth != null&& serverauth.equalsIgnoreCase("true")) {
	                session = Session.getInstance(props, authen);
	            } else {
	                session = Session.getInstance(props);
	            }
	            // Define message
	            Message message = new MimeMessage(session);
	            message.setFrom(new InternetAddress(senderadress));
	            /*
	            * Multiple(多个接收者)
	            */
	            if ( email_to != null && !email_to.trim().equals( "" )) {
	                String tos[] = email_to.trim().split(",");
	                Address toAdd[] = new Address[tos.length];
	                for ( int i = 0; i < toAdd.length; i++ ) {
	                    toAdd[i] = new InternetAddress( tos[i] );
	                }
	                message.addRecipients(Message.RecipientType.TO, toAdd);        
	            }            
	            message.setSubject(email_subject);
	            message.setSentDate(new Date());
	            /*
	            * Body created
	            */
	            BodyPart messageBodyPart = new MimeBodyPart();
	            /*
		        * pushing the bosy text
		        */
	            messageBodyPart.setText(email_body);
	            Multipart multipart = new MimeMultipart();

	            //设置信件的附件(用远程文件作为附件)
	            if (files!=null && files.trim().length()>0) {
		            MimeBodyPart mdp=new MimeBodyPart();
		            URLDataSource ur=new URLDataSource(new java.net.URL("http://localhost:8080/Patent/UploadFile/"+files));
		            DataHandler dh=new DataHandler(ur);
		            mdp.setFileName(files);
		            mdp.setDataHandler(dh);
		            multipart.addBodyPart(mdp);
	            }

	            multipart.addBodyPart(messageBodyPart);
	            /*
	            * allowing support for attachment
	            */
	            message.setContent(multipart);
	            message.saveChanges();
	            Transport.send(message);
	        } catch (Exception mex) {
	            result = false;
	            mex.printStackTrace();
	        }
	        return result;
	    }

	    /**
	    * Inner class
	    */
	    private class JackAuthenticator extends javax.mail.Authenticator {
	        public PasswordAuthentication getPasswordAuthentication() {
	            //return new PasswordAuthentication(MAIL_SERVER_USER, SERVER_PASSWORD);
	            return new PasswordAuthentication(senderadress, senderpassword);
	        }
	    }
}
